import Sockets from '../services/socket';

export default {
  namespace: 'chat',
  state: {
    sys: {},
    msg: [],
  },
  reducers: {
    sys(state, { payload: sys }) {
      return { ...state, sys };
    },
    message(state, { payload: msg }) {
      state.msg.push(msg);
      return { ...state };
    },
  },
  effects: {
    submit({ payload: { roomnum, speaker, news } }) {
      Sockets.emit('send', { roomnum, speaker, news });
    },
    *userMsg({ payload: usermsg }, { put }) {
      yield put({ type: 'message', payload: usermsg });
    },
    leave({ payload: { userName, roomNum } }) {
      const id = Sockets.id;
      Sockets.emit('leave', { userName, roomNum, id });
    },
  },
  subscriptions: {
    // watchSys({ dispatch }) {
    //   Sockets.on('sys', (data) => {
    //     console.log(data);
    //     dispatch({ type: 'sys', payload: data.msg });
    //   });
    // },
    watchMsg({ dispatch }) {
      Sockets.on('accept', (data) => {
        dispatch({ type: 'message', payload: data });
      });
    },
  },
};
